package com.whiteape.book.utils;

import android.content.Context;
import android.text.TextUtils;


import androidx.annotation.StringRes;

import com.whiteape.book.WaApp;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.manager.ReplaceRuleManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.ReplaceRuleBean;
import com.zqc.opencc.android.lib.ChineseConverter;
import com.zqc.opencc.android.lib.ConversionType;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import static com.whiteape.book.core.manager.ReadSettingManager.SHARED_READ_CONVERT_TYPE;


/**
 * Created by newbiechen on 17-4-22.
 * 对文字操作的工具类
 */

public class StringUtils {
    private static final String TAG = "StringUtils";
    private static final int HOUR_OF_DAY = 24;
    private static final int DAY_OF_YESTERDAY = 2;
    private static final int TIME_UNIT = 60;
    private static final String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";

    public static boolean isBase64(String str) {
        return Pattern.matches(base64Pattern, str);
    }

    //将时间转换成日期
    public static String dateConvert(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
        return format.format(date);
    }

    //将日期转换成昨天、今天、明天
    public static String dateConvert(String source, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
        Calendar calendar = Calendar.getInstance();
        try {
            Date date = format.parse(source);
            long curTime = calendar.getTimeInMillis();
            calendar.setTime(date);
            //将MISC 转换成 sec
            long difSec = Math.abs((curTime - date.getTime()) / 1000);
            long difMin = difSec / 60;
            long difHour = difMin / 60;
            long difDate = difHour / 60;
            int oldHour = calendar.get(Calendar.HOUR);
            //如果没有时间
            if (oldHour == 0) {
                //比日期:昨天今天和明天
                if (difDate == 0) {
                    return "今天";
                } else if (difDate < DAY_OF_YESTERDAY) {
                    return "昨天";
                } else {
                    DateFormat convertFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String value = convertFormat.format(date);
                    return value;
                }
            }

            if (difSec < TIME_UNIT) {
                return difSec + "秒前";
            } else if (difMin < TIME_UNIT) {
                return difMin + "分钟前";
            } else if (difHour < HOUR_OF_DAY) {
                return difHour + "小时前";
            } else if (difDate < DAY_OF_YESTERDAY) {
                return "昨天";
            } else {
                DateFormat convertFormat = new SimpleDateFormat("yyyy-MM-dd");
                String value = convertFormat.format(date);
                return value;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String toFirstCapital(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    public static String getString(@StringRes int id) {
        return WaApp.getInstance().getResources().getString(id);
    }

    public static String getString(@StringRes int id, Object... formatArgs) {
        return WaApp.getInstance().getResources().getString(id, formatArgs);
    }

    /**
     * 将文本中的半角字符，转换成全角字符
     *
     * @param input
     * @return
     */
    public static String halfToFull(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 32) //半角空格
            {
                c[i] = (char) 12288;
                continue;
            }
            //根据实际情况，过滤不需要转换的符号
            //if (c[i] == 46) //半角点号，不转换
            // continue;

            if (c[i] > 32 && c[i] < 127)    //其他符号都转换为全角
                c[i] = (char) (c[i] + 65248);
        }
        return new String(c);
    }

    //功能：字符串全角转换为半角
    public static String fullToHalf(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) //全角空格
            {
                c[i] = (char) 32;
                continue;
            }

            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    //繁簡轉換
    public static String convertCC(String input, Context context) {
        ConversionType currentConversionType = ConversionType.S2TWP;
        int convertType = SharedPreUtils.getInstance().getInt(SHARED_READ_CONVERT_TYPE, 0);

        //
        convertType = ReadSettingManager.getInstance().getFanti() ? 3 : 7;
        if (input.length() == 0)
            return "";

        switch (convertType) {
            case 1:
                currentConversionType = ConversionType.TW2SP;
                break;
            case 2:
                currentConversionType = ConversionType.S2HK;
                break;
            case 3:
                currentConversionType = ConversionType.S2T;
                break;
            case 4:
                currentConversionType = ConversionType.S2TW;
                break;
            case 5:
                currentConversionType = ConversionType.S2TWP;
                break;
            case 6:
                currentConversionType = ConversionType.T2HK;
                break;
            case 7:
                currentConversionType = ConversionType.T2S;
                break;
            case 8:
                currentConversionType = ConversionType.T2TW;
                break;
            case 9:
                currentConversionType = ConversionType.TW2S;
                break;
            case 10:
                currentConversionType = ConversionType.HK2S;
                break;
        }

        return (convertType != 0) ? ChineseConverter.convert(input, currentConversionType, context) : input;
    }

    public static boolean isJsonFormat(String str) {
        return isJsonObjFormat(str) || isJsonArrFormat(str);

    }

    public static boolean isJsonObjFormat(String str) {
        if (str == null) {
            return false;
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(str.trim())) {
            return false;
        }
        str = str.trim();
        return (str.startsWith("{") && str.endsWith("}"));

    }

    public static boolean isJsonArrFormat(String str) {
        if (str == null) {
            return false;
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(str.trim())) {
            return false;
        }
        str = str.trim();
        return (str.startsWith("[") && str.endsWith("]"));

    }

    public static boolean isUrlFormat(String str) {
        if (str == null) {
            return false;
        }
        return str.trim().startsWith("http");
    }

    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isAnyEmpty(CharSequence... css) {
        if (css == null || css.length == 0) {
            return true;
        }
        for (CharSequence cs : css) {
            if (isEmpty(cs)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isTrimEmpty(String text) {
        if (text == null) return true;
        if (text.length() == 0) return true;
        return text.trim().length() == 0;
    }

    public static String formatHtml(String html) {
        if (TextUtils.isEmpty(html)) return "";
        return html.replaceAll("(?i)<(br[\\s/]*|/*p.*?|/*div.*?)>", "\n")// 替换特定标签为换行符
                .replaceAll("<[script>]*.*?>|&nbsp;", "")// 删除script标签对和空格转义符
                .replaceAll("\\s*\\n+\\s*", "\n　　")// 移除空行,并增加段前缩进2个汉字
                .replaceAll("^[\\n\\s]+", "　　")//移除开头空行,并增加段前缩进2个汉字
                .replaceAll("[\\n\\s]+$", "");//移除尾部空行
    }

    /**
     * 去除字符串中头部和尾部所包含的空格（包括:空格(全角，半角)、制表符、换页符等）
     *
     * @param s
     * @return
     */
    public static String trim(String s) {
//        if (null != s && !"".equals(s)) {
//            result = s.replaceAll("^[　*| *| *|\\s*]*", "").replaceAll("[　*| *| *|\\s*]*$", "");
//        }
        return s.replaceAll("\\s", "").trim();

    }

    public static String formatTime(long seconds) {
        String time;

        if (seconds < 60) {
            time = String.format(Locale.CHINA, "00:%02d", seconds % 60);
        } else if (seconds < 3600) {
            time = String.format(Locale.CHINA, "%02d:%02d", seconds / 60, seconds % 60);
        } else {
            time = String.format(Locale.CHINA, "%02d:%02d:%02d", seconds / 3600, seconds % 3600 / 60, seconds % 60);
        }
        return time;

    }

    public static String getColorHexString(int color) {
        String s = "#";
        int colorStr = (color & 0xff000000) | (color & 0x00ff0000) | (color & 0x0000ff00) | (color & 0x000000ff);
        s = s + Integer.toHexString(colorStr);
        return s;
    }

    public static String filterNovelContentByReplaceRule(String content, CollectionMediaBean collectionMediaBean) {
        List<ReplaceRuleBean> enabledReplaceRuleBeanList = ReplaceRuleManager.getInstance().getAllEnabledReplaceRules();
        if (enabledReplaceRuleBeanList == null || enabledReplaceRuleBeanList.size() == 0) {
            return content;
        }
        String bookName = collectionMediaBean.getTitle();

        String siteHostUrl = null;
        try {
            if (collectionMediaBean.getSiteSourceBean() != null) {

                siteHostUrl = collectionMediaBean.getSiteSourceBean().getSiteHostUrl();
            }
            //替换
            for (ReplaceRuleBean replaceRule : enabledReplaceRuleBeanList) {
                if (isUseTo(replaceRule.getUseTo(), siteHostUrl, bookName)) {
                    content = content.replaceAll(replaceRule.getFixedRegex(), replaceRule.getReplacement()).trim();
                }
            }
        } catch (Exception ignored) {
        }
        return content;
    }

    private static boolean isUseTo(String useTo, String bookTag, String bookName) {
        return TextUtils.isEmpty(useTo)
                || (!StringUtils.isEmpty(bookTag) && useTo.contains(bookTag))
                || useTo.contains(bookName);
    }


}
